import vue from 'vue'
import axios from 'axios';
// import { for } from 'core-js/fn/symbol';

import format from './format'
import config from './configs'

// console.log(config);

// import zip from '@zip.js/zip.js'

// console.log(zip);

var treeObject = {};

const bus = new vue({
    data() {
        return {
            allData: [],
            treeData: [],
            models: [],
            IP: null,
        }
    },
    methods: {
        guid() {
            return 'G' + 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0,
                    v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        },
        /**
         * 获取Swgger 接口信息参数对象
         *
         * @param {*} url
         * @return {*} 
         */
        getDoc(url) {
            let reg = /configObject\s+=\s+JSON\.parse\((.+?)\)/;
            let IP = url.split('/')[2];
            this.IP = 'http://' + IP;
            return axios.get(url).then((res) => {
                let configObject;
                res.data.replace(reg, function ($i) {
                    eval($i);
                });
                let requireArray = [];
                for (let i = 0; i < configObject.urls.length; i++) {
                    const element = configObject.urls[i];
                    requireArray.push(axios.get(this.IP + element.url).then(res => res.data));
                }
                return axios.all(requireArray);
            }).then(res => {
                this.initData(res);
                return res
            })
        },
        getDevDoc() {
            return new Promise((resolve, reject) => {
                // 一段耗时的异步操作
                this.initData(config);
                resolve() // 数据处理完成
                // reject('失败') // 数据处理出错
            })
        },
        /**
         * 初始化 树形结构图
         *
         * @param {*} data
         */
        initData(data) {
            var tree = [];
            data.forEach(ele => {
                var folder = {};
                folder.id = this.guid();
                folder.title = ele.info.title;
                // console.log(folder.title);
                folder.children = [];
                folder.models = {};
                folder.Schemas = {};
                var _models = ele.components.schemas;
                for (const key in _models) {
                    const element = _models[key];
                    folder.Schemas[key] = element;
                    folder.models['#/components/schemas/' + key] = format.Models(element, key);
                };
                for (const url in ele.paths) {
                    const method = ele.paths[url];
                    for (const type in method) {
                        const _file = method[type];
                        var file = {};
                        file.id = this.guid();
                        file.title = _file.summary;
                        file.url = url;
                        file.type = type;
                        file.key = _file.tags[0];
                        file.query = _file.parameters;
                        _file.requestBody && (() => {
                            file.body = {};
                            for (const key in _file.requestBody.content) {
                                const element = _file.requestBody.content[key];
                                if (key != 'application/*+json' && key != 'text/json' && key != 'application/json-patch+json') {
                                    file.body[key] = format.Models(element.schema, key);
                                }
                            }
                        })();
                        file.parent = folder.id;
                        _file.responses && (function () {
                            if (!_file.responses) {
                                return;
                            }
                            if (!_file.responses['200']) {
                                return;
                            }
                            if (!_file.responses['200'].content) {
                                return;
                            }
                            if (!_file.responses['200'].content['application/json']) {
                                return;
                            }
                            if (!_file.responses['200'].content['application/json'].schema) {
                                return;
                            }
                            file.responses = format.Models(_file.responses['200'].content['application/json'].schema, '200');
                        })();
                        folder.children.push(file);
                    };
                };
                tree.push(folder);
                treeObject[folder.id] = folder;
            });
            this.treeData = tree;
        },
        getFolder(id) {
            return treeObject[id]
        },
        formatJson(type) {
            var str = this[type].getValue();
            str = this.beautify(str);
            this[type].setValue(str);
        },
        beautify(source) {
            function looks_like_html(source) {
                var trimmed = source.replace(/^[ \t\n\r]+/, '');
                return trimmed && (trimmed.substring(0, 1) === '<');
            };
            var output,
                opts = {
                    // brace_style : "expand"
                };
            opts.indent_char = ' ';
            opts.preserve_newlines = "-1";
            if (looks_like_html(source)) {
                output = html_beautify(source, opts);
            } else {
                output = js_beautify(source, opts);
            };
            return output;
        },

        renderSingleFile(folder) {
            var key = '';
            var folderStrArray = [];
            var _nameKeys = [];
            folder.children.forEach(child => {
                var $name = child.url.split('/')[3];
                key = child.key;
                if (_nameKeys.includes($name)) {
                    $name += '_' + child.type;
                };

                if (child.responses) {
                    try {
                        var _String = format.String(child.responses, folder.models);
                        var _responses = '// 返回值数据模型 \n' + 'var responsesData = ' + this.beautify(_String) + '\n';
                    } catch (error) {
                        var _responses = '';
                    }
                };


                var _bodyStr = '';
                for (const key in child.body) {
                    const element = child.body[key];
                    var _String = format.String(element, folder.models);
                    _bodyStr += '// Body参数 -- 类型 : ' + key + '\n';
                    _bodyStr += 'var bodyData = ' + this.beautify(_String);
                }

                const renderAnnotation = item => ' // ' + item.annotate + ' (' + item.type + ') ' + (item.checked ? '必填' : '') + '\n';
                var _queryString = '';
                var _queryArray = [];
                if (child.query) {
                    child.query.forEach(ele => {
                        var _data = {};
                        _data.key = ele.name;
                        _data.type = ele.schema.type;
                        _data.annotate = ele.description || '';
                        _data.checked = !ele.nullable;
                        _queryArray.push(_data);
                    });

                    if (_queryArray.length) {
                        _queryString = '{'
                        for (let i = 0; i < _queryArray.length; i++) {
                            var item = _queryArray[i];
                            if (item.type == 'object') {
                                _queryString += (item.key + ': {},' + renderAnnotation(item));
                            } else {
                                _queryString += ((item.key ? item.key : '\'\'') + ':' + '\'\',' + renderAnnotation(item));
                            }
                        };
                        _queryString += '}'
                        _queryString = this.beautify(_queryString);
                        _queryString = '// url 参数 \n' + 'var query =' + _queryString;
                    }
                }
                var str = `
                   
    /**
     * ${child.title || child.url}
     *
     * @param {*} options
     * @return {*} 
     * @memberof _$Service
     * @example
     * ${_queryString.replace('\n', '\n\t * ')}
     * ${_bodyStr.replace('\n', '\n\t * ')}
     * ${_responses.replace('\n', '\n\t * ')}
    */
    '${$name}': function (options) {
        return request.${child.type}('${child.url}', options, 'pro')
    },

`;
                folderStrArray.push(str);
            });
            var _str = `import request from './request.js'
// ${folder.title}
export default {`;
            folderStrArray.forEach(ele => {
                _str += '\t' + ele;
            })
            _str += '};';
            return {
                key: key,
                str: _str,
            }
        },
        downloadJSFile() {
            var FileObject = {};
            this.treeData.forEach(ele => {
                var codeString = this.renderSingleFile(ele);
                FileObject[codeString.key] = codeString.str;
            })
            return FileObject
        },

    }
});

export default bus